<template>
    <div class="view" v-wechat-title="$route.meta.title=`购物车（${cartArrayList.length})`">

        <nav-bar :title="`购物车（${cartArrayList.length})`">
            <div class="back" slot="left" @click="back">
                <i class="iconfont icon-fanhui"></i>
            </div>
        </nav-bar>
        <div class="skeleton-preview" style="z-index: 10" v-if="skeletonShow">
            <img src="@/assets/skeleton/skeleton-shopping-cart.png">
        </div>
        <div class="cart-wrap" v-else>
            <cube-scroll :data="cartArrayList">
                <cube-swipe>
                    <div class="cart-group" v-for="(group,key,gIdx) in cartDataList" :key="key" :data-id="key">
                        <div class="cart-group-head">
                            <div class="cart-group-head-checkbox-btn" @click="tapShopCheckbox(key,group.checked)"></div>
                            <cube-checkbox v-model="group.checked" class="cart-group-head-checkbox">
                                <div class="cart-group-head-name">{{group.supplierName}}</div>
                            </cube-checkbox>
                        </div>
                        <div class="cart-group-list">
                            <transition-group name="swipe" tag="div">
                                <div class="cart-group-cell" v-for="(item,idx) in group.childList" :key="item.cartId">
                                    <cube-swipe-item ref="swipeItem" :btns="swipeBtn" :index="item.countIndex" @btn-click="onBtnClick">
                                        <div class="cart-group-cell-context">
                                            <div class="cart-group-cell-checkbox">
                                                <cube-checkbox v-model="item.checked" :option="{label:''}"></cube-checkbox>
                                                <div class="cart-group-cell-checkbox-btn" @click="tapItemCheckbox(key,idx,item.checked,item.cartId)"></div>
                                            </div>
                                            <div class="cart-group-cell-picture">
                                                <img :src="item.image[0].file_path+'?imageView2/2/w/125'">
                                            </div>
                                            <div class="cart-group-cell-info">
                                                <div class="cart-group-cell-info-name ellipsis-2">
                                                    {{item.name}}
                                                </div>
                                                <div class="cart-group-cell-info-spec" v-if="item.item_sku.item_attr">
                                                    {{item.item_sku.item_attr}}
                                                </div>
                                                <div class="cart-group-cell-info-number">
                                                    <div class="cart-group-cell-info-price">{{item.item_price}}</div>
                                                    <number-box :readonly="true" v-model='item.total_num' @focus="boxFocus" @blur="boxBlur" :min='1' :max="item.stock_num"
                                                                @clickAdd="addCartNumber(key,idx)" @clickSub="subCartNumber(key,idx)"></number-box>
                                                </div>
                                            </div>
                                        </div>
                                    </cube-swipe-item>
                                </div>
                            </transition-group>
                        </div>
                    </div>
                </cube-swipe>
            </cube-scroll>
        </div>
        <div class="cart-bottom">
            <template v-if="cartArrayList.length > 0">
                <cube-checkbox class="cart-bottom-all" v-model="selectAll" :option="{label:'全选'}" style="padding-left: 0;"></cube-checkbox>
                <div class="cart-bottom-all-btn" @click="tapSelectAll"></div>
            </template>
            <div class="" v-else></div>
            <div class="cart-bottom-right">
                <div class="cart-bottom-total">合计：</div>
                <div class="cart-bottom-money" v-html="budget"></div>
                <div class="cart-bottom-pay" @click="submitOrder">结算<span v-if="checkedItemNumber>0">({{checkedItemNumber}})</span></div>
            </div>
        </div>
    </div>
</template>
<script lang="ts">
    import {Component, Vue, Watch} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";

    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";
    import CommonUnit from "@/unit/CommonUnit";
    import Heart from "@/unit/Heart";
    import UserEntity from "@/entity/UserEntity";
    import {exitUser, updateDataCache} from "@/store/dispatches";
    import NumberBox from "@/components/aui/NumberBox.vue";
    import NavBar from "@/components/aui/NavBar.vue";

    @Component({
        components: {
            NavBar, NumberBox
        }
    })
    export default class ShoppingCart extends Scene {

        @State("UserStore")
        public user!: InterfaceUser;

        @State("DataCacheStore")
        public dataCache!: any;

        private skeletonShow: boolean = true;
        private cartDataList: any = {};
        private cartArrayList: any[] = [];
        private selectAll: boolean = false;
        private focus: boolean = false;
        private loadToast: any = "";
        private swipeBtn: any[] = [{
            action: "delete",
            text: "删除",
            color: "#ff3a32"
        }];


        private get checkedItemNumber(): number {
            let count = 0;
            for (const key in this.cartDataList) {
                for (const i in this.cartDataList[key].childList) {
                    if (this.cartDataList[key].childList[i].checked) {
                        count += 1;
                    }
                }
            }
            return count;
        }

        private get checkedCartIdList(): string[] {
            const checkedCartIdList: string[] = [];
            for (const key in this.cartDataList) {
                for (const i in this.cartDataList[key].childList) {
                    if (this.cartDataList[key].childList[i].checked) {
                        checkedCartIdList.push(this.cartDataList[key].childList[i].cartId);
                    }
                }
            }
            return checkedCartIdList;
        }

        private get budget(): number | string {
            let budget: number | string = 0;
            for (const key in this.cartDataList) {
                for (const i in this.cartDataList[key].childList) {
                    if (this.cartDataList[key].childList[i].checked) {
                        budget += Number(this.cartDataList[key].childList[i].item_price) * Number(this.cartDataList[key].childList[i].total_num);
                    }
                }
            }
            if (Number(budget) === 0) {
                return 0;
            }
            budget = Math.round(parseFloat(String(budget)) * 100) / 100;
            let xsd = String(budget).split(".");
            if (xsd.length == 1) {
                budget = String(budget) + ".00";
            }
            if (xsd.length > 1) {
                if (xsd[1].length < 2) {
                    budget = String(budget) + "0";
                } else {
                    budget = String(budget) + "0";
                }
            }
            const budgetForm = String(budget).split(".");
            return `${budgetForm[0]}.<span class="decimal-point">${budgetForm[1]}</span>`;
        }

        private activated() {
            this.getCartList();
        }

        private created(): void {
            this.loadToast = (<any> this).$createToast({
                time: 0,
                txt: "获取购物车数据，请稍后",
                mask: true
            }).show();
            this.cartDataList = this.dataCache.cartObjectData;
            this.cartArrayList = this.dataCache.cartListData;
            if (this.cartArrayList.length > 0) {
                this.skeletonShow = false;
            }
            setTimeout(() => {
                this.getCartList();
            }, 500);
        }

        private back() {
            this.navigateBack();
        }


        private tapSelectAll(): void {
            this.selectAll = !this.selectAll;
            for (const key in this.cartDataList) {
                this.$set(this.cartDataList[key], "checked", this.selectAll);
                for (const i in this.cartDataList[key].childList) {
                    this.$set(this.cartDataList[key].childList[i], "checked", this.selectAll);
                }
            }
        }

        private tapShopCheckbox(key: string, checked: boolean): void {
            this.$set(this.cartDataList[key], "checked", !checked);
            for (const i in this.cartDataList[key].childList) {
                this.$set(this.cartDataList[key].childList[i], "checked", !checked);
            }
            this.selectAll = this.checkedItemNumber === this.cartArrayList.length;

        }

        private tapItemCheckbox(key: string, i: number, checked: boolean, cartId: string): void {
            this.$set(this.cartDataList[key].childList[i], "checked", !checked);
            this.$nextTick(() => {
                this.selectAll = this.checkedItemNumber === this.cartArrayList.length;
                let itemCheckedCount = 0;
                for (const i in this.cartDataList[key].childList) {
                    if (this.cartDataList[key].childList[i].checked) {
                        itemCheckedCount += 1;
                    }
                }
                this.$set(this.cartDataList[key], "checked", itemCheckedCount === this.cartDataList[key].childList.length);
            });
        }

        private async getCartList(): Promise<any> {
            try {
                const res = await Http.get(this.api.getCartLists, {}, {token: this.user.token});
                if (res.code === 1) {
                    this.cartDataHandle(res.data);
                    // this.cartDataList = Object.assign(this.cartDataList, this.cartDataHandle(res.data));
                    this.loadToast.hide();
                } else {
                    this.globalSingleResultToast(res);
                }
                this.skeletonShow = false;
            } catch (e) {
                this.loadToast.hide();
            }
        }

        private cartDataHandle(obj: any): boolean {
            let count = 0;
            this.cartArrayList.splice(0, this.cartArrayList.length);
            this.cartDataList = {};
            for (const oldkey in obj) {
                const objData: any = {};
                const oldKeyArray = oldkey.split("_");
                const newKey = `supplierId-${oldKeyArray[0]}`;
                objData.supplierName = oldKeyArray[1];
                // cartDataList[newKey].checked = false;
                objData.supplierId = oldKeyArray[0];
                objData.checked = false;
                objData.childLength = obj[oldkey].length;
                objData.childChecked = [];
                objData.childList = [];
                for (const data  of obj[oldkey]) {
                    data.cartId = `${data.item_id}_${data.item_sku.spec_sku_id}`;
                    data.checked = false;
                    data.total_num = Number(data.total_num);
                    data.oldCount = Number(data.total_num);
                    data.countIndex = count;
                    count = count + 1;
                    this.cartArrayList.push(data);
                    objData.childList.push(data);
                }
                this.$set(this.cartDataList, newKey, objData);

            }
            this.$nextTick(() => {
                updateDataCache({cartObjectData: this.cartDataList});
                updateDataCache({cartListData: this.cartArrayList});
            });
            return true;
        }

        private async addCartNumber(key: string, i: number): Promise<any> {
            this.itemNumberHandle(key, i, "add");
        }

        private subCartNumber(key: string, i: number): void {
            this.itemNumberHandle(key, i, "sub");
        }

        private async itemNumberHandle(key: string, i: number, type: string): Promise<any> {
            const item_id = this.cartDataList[key].childList[i].item_id;
            const newCount = this.cartDataList[key].childList[i].total_num;
            const oldCount = this.cartDataList[key].childList[i].oldCount;
            const item_sku_id = this.cartDataList[key].childList[i].item_sku.spec_sku_id;
            let api: string = "";
            if (type === "add") {
                api = this.api.cartAdd;
            } else {
                api = this.api.cartSub;
            }
            const res = await Http.post(api, {item_id, item_sku_id, item_num: 1}, {token: this.user.token});
            if (res.code === 1) {
                this.$set(this.cartDataList[key].childList[i], "oldCount", res.data.num);
                this.$set(this.cartDataList[key].childList[i], "total_num", res.data.num);
            } else {
                this.$set(this.cartDataList[key].childList[i], "total_num", oldCount);
            }
        }

        private boxFocus(): void {
            this.focus = true;
        }

        private boxBlur(): void {
            this.focus = false;
        }

        private async onBtnClick(btn: any, index: number): Promise<any> {
            if (btn.action === "delete") {
                this.loadToast = (<any> this).$createToast({
                    time: 0,
                    txt: "正在删除...请稍后",
                    mask: true
                }).show();
                const res = await Http.post(this.api.cartDelete, {sku_id: this.cartArrayList[index].cartId}, {token: this.user.token});
                if (res.code === 1) {
                    setTimeout(() => {
                        this.getCartList();
                        this.loadToast.hide();
                    }, 1000);
                } else {
                    this.globalSingleResultToast(res);
                }
            }
        }

        private submitOrder() {
            if (this.checkedCartIdList.length > 0) {
                this.navigateTo({
                    name: "orderConfirm",
                    query: {cartIds: this.checkedCartIdList.join(","), type: 2}
                });
            }

        }
    }
</script>

<style scoped lang="stylus">
    .view
        width 100vw;
        height 100vh;
        background $theme-page-common-background-color;

        .cart-wrap
            width 100vw;
            height calc(100vh - 50px - var(--safe-area-inset-bottom));
            padding-top calc(44px + var(--safe-area-inset-top))

            .cart-group
                margin 12px;
                border-radius 12px;
                overflow hidden;
                background #fff

                .cart-group-head
                    height 42px;
                    background #fff;
                    display flex;
                    align-items flex-start;
                    position relative;

                    .cart-group-head-checkbox-btn
                        width 32px;
                        height 32px;
                        position absolute;
                        left 4px;
                        top 5px;
                        z-index 50;


                    .cart-group-head-checkbox
                        padding-left 12px;
                        font-size 15px;

                        >>> .cube-checkbox-label
                            font-size 13px;

                    .cart-group-head-name
                        color #333;
                        font-size 12px;
                        padding-left 6px;

                .cart-group-list
                    background $theme-thin-x5-color;

                    .cart-group-cell-context
                        display flex;
                        padding 10px 0
                        justify-content center;

                        .cart-group-cell-checkbox
                            width 44px;
                            height 92px;
                            display flex;
                            justify-content center;
                            align-items center;
                            position relative

                            .cart-group-cell-checkbox-btn
                                width 34px;
                                height 34px;
                                position absolute;
                                z-index 50;
                                left 5px;
                                top 29px;


                        .cart-group-cell-picture
                            width 92px;
                            height 92px;
                            flex 0 0 92px;
                            border-radius 8px;
                            overflow hidden;

                            img
                                width 92px;
                                height 92px;
                                display block

                        .cart-group-cell-info
                            padding 0 12px;
                            flex 1;
                            display flex
                            flex-direction column;
                            min-height 92px;

                            .cart-group-cell-info-name
                                line-height 19px;
                                font-size 14px;

                            .cart-group-cell-info-spec
                                background #f8f4f1;
                                padding 4px 1px;
                                color #999;
                                font-size 11px;
                                line-height 15px;
                                margin-top 1px;

                            .cart-group-cell-info-number
                                margin-top 5px;
                                display flex;
                                flex-direction column;
                                justify-content space-between;
                                align-items flex-end

                                .cart-group-cell-info-price
                                    font-size 15px;
                                    padding-bottom 5px;
                                    color $theme-common-color;
                                    align-self flex-start

                                    &::before
                                        font-size 12px;
                                        content '￥'

                                >>> .number-box
                                    .number-box-minus, .number-box-plus, input
                                        background #fff;

                                    .number-box-disabled
                                        opacity .5;


        .cart-bottom
            height calc(50px + var(--safe-area-inset-bottom));
            padding 0 12px var(--safe-area-inset-bottom) 12px;
            width 100vw;
            background #fff;
            display flex;
            position fixed;
            bottom 0;
            z-index 113;
            justify-content space-between;
            align-items center;

            .cart-bottom-all-btn
                width 70px;
                height 50px;
                position absolute;
                z-index 50;

            .cart-bottom-all
                font-size 17px;

                >>> .cube-checkbox-label
                    font-size 13px;

            .cart-bottom-right
                height 50px;
                display flex;
                justify-content center;
                align-items center;

                .cart-bottom-total
                    font-size 13px;
                    color #4f4f4f;

                .cart-bottom-money
                    color $theme-common-color;
                    font-size 17px;
                    padding-right 6px;

                    &::before
                        content '￥';
                        font-size 12px;


                .cart-bottom-pay
                    width 100px;
                    height 38px;
                    background $theme-common-gradient;
                    line-height 38px;
                    color #fff;
                    border-radius 20px;
                    text-align center;
                    font-size 14px;

                    span
                        font-size 12px;

</style>
